package com.djzz.app.common_util.net;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.djzz.app.common_util.net.bean.PostBean;
import com.djzz.app.common_util.net.bean.ResponseBean;
import com.djzz.app.common_util.utils.LogUtil;

import java.lang.reflect.Field;

/**
 * Created by d on 2017/8/31.
 */

public class HttpHelper <T extends ResponseBean>{

    private int method = Request.Method.POST;
    private PostBean postBean;
    private HttpCallBack<T> callBack;
    private Class<T>responseClass;
    private String url;

    public HttpHelper(String url, PostBean postBean, HttpCallBack<T> callBack, Class<T> responseClass) {

        this(Request.Method.POST, url, postBean, callBack, responseClass);
    }

    public HttpHelper( int method,String url, PostBean postBean, HttpCallBack<T> callBack, Class<T> responseClass) {
        this.method = method;
        this.postBean = postBean;
        this.callBack = callBack;
        this.responseClass = responseClass;
        this.url = url;
    }

    public HttpRequest<T> getRequest(){

        Response.Listener<T> successListener = new Response.Listener<T>() {
            @Override
            public void onResponse(T response) {
                callBack.onSusscess(response);
            }
        };

        Response.ErrorListener errorListener = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                callBack.onError(error);
            }
        };

        HttpRequest<T> request;

        if(method == Request.Method.POST){ // post 请求

            String json = postBean.getJson();
            LogUtil.i("hh 请求报文：", json);
            request = new HttpRequest<T>(method, responseClass, url, json, successListener, errorListener);
        }else{ // get 请求

            StringBuilder sb = new StringBuilder();
            sb.append("?str=").append(postBean.getJson());
            Class mClass = postBean.getClass();
            Field[] fields = mClass.getFields();
            for ( Field field : fields){
                try {
                    String value = field.get(postBean).toString();
                    sb.append(field.getName()).append("=").append(value).append("&");
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }

            request = new HttpRequest<T>(Request.Method.GET, responseClass, url+sb.toString(), successListener, errorListener);
        }

        return request;
    }

    public void start(){
        HttpManager.addQueue(this);
    }
}
